package ezonsport.android.service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.j256.ormlite.stmt.QueryBuilder;

import android.util.Log;

import ezonsport.android.core.stepSystem.SportPlan;
import ezonsport.android.data.DataHelper;
import ezonsport.android.data.OrmliteDataContext;

/**
 * 运动目标管理服务
 * 
 * @author Administrator chenbei
 * @since 2012-6-11
 * 
 */
public class GoalManageService {
	private OrmliteDataContext ctx;

	public GoalManageService(DataHelper dataHelper) {
		ctx = new OrmliteDataContext(dataHelper);
	}

	/**
	 * 获取最近的运动目标
	 * 
	 * @return
	 */
	public int getLatestGoal() {
		try {
			// 获取所有运动计划
			QueryBuilder<SportPlan, Long> qb = ctx.getQueryBuilder(
					SportPlan.class, long.class);
			qb.orderBy("formulateTime", false);
			List<SportPlan> sportPlans = ctx.query(SportPlan.class, long.class,
					qb.prepare());
			// 获取当前的运动计划
			int currentGoal = sportPlans.get(0).getGoalStep();
			return currentGoal;
		} catch (Exception e) {
		}
		return 0;
	}

	/**
	 * 设置目标
	 * 
	 * @param goalStep
	 */
	public void setLatestGoal(int goalStep) {
		try {
			ctx.beginTransaction();

			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Calendar dateCalendar = Calendar.getInstance();// 以当前时间作为运动计划时间
			String planTime = format.format(dateCalendar.getTime());
			// 首先获取最新目标，判断是否是当天
			QueryBuilder<SportPlan, Long> qb = ctx.getQueryBuilder(
					SportPlan.class, long.class);
			qb.orderBy("formulateTime", false);
			List<SportPlan> sportPlans = ctx.query(SportPlan.class, long.class,
					qb.prepare());
			// 获取当前的运动计划
			SportPlan latestPlan = sportPlans.get(0);
			// 如果是，则更新目标，否则，添加目标
			if (latestPlan.getFormulateTime().equals(format.parse(planTime))) {
				latestPlan.setGoalStep(goalStep);
				ctx.update(latestPlan, SportPlan.class, long.class);
			} else {

				SportPlan sportPlan = new SportPlan();
				sportPlan.setFormulateTime(format.parse(planTime));
				sportPlan.setGoalStep(goalStep);
				ctx.add(sportPlan, SportPlan.class, long.class);
			}

			ctx.commit();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ctx.rollback();
		}

	}

	/**
	 * 根据计划时间获取目标步数
	 * 
	 * @param planTime
	 * @return goal
	 */
	public int getGoalByDate(Date planTime) {
		try {
			// 对日期参数格式化
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String dateString = format.format(planTime);
			Date formulateTime = format.parse(dateString);
			// 获取全部运动计划
			QueryBuilder<SportPlan, Long> qb = ctx.getQueryBuilder(
					SportPlan.class, long.class);
			qb.orderBy("formulateTime", true);
			List<SportPlan> sportPlans = ctx.query(SportPlan.class, long.class,
					qb.prepare());
			for (SportPlan sportPlan : sportPlans) {
				Log.d("SportPlan", sportPlan.getFormulateTime().toString());
			}
			// 查找指定日期的计划
			for (SportPlan sportPlan : sportPlans) {
				// 存在
				if (formulateTime.equals(sportPlan.getFormulateTime())) {
					return sportPlan.getGoalStep();
				}
			}
			// 不存在，则插入
			SportPlan sportPlan = new SportPlan();
			sportPlan.setFormulateTime(formulateTime);
			// 如果实际运动日期在计划日期之前，则设定目标步数为默认值：3000
			int size = sportPlans.size();
			if (formulateTime.before(sportPlans.get(0).getFormulateTime())) {
				sportPlan.setGoalStep(3000);
			} else if (formulateTime.after(sportPlans.get(size - 1)
					.getFormulateTime())) {
				sportPlan.setGoalStep(sportPlans.get(size - 1).getGoalStep());
			} else {
				for (int i = 0; i < sportPlans.size() - 1; i++) {
					if (formulateTime.after(sportPlans.get(i)
							.getFormulateTime())
							&& formulateTime.before(sportPlans.get(i + 1)
									.getFormulateTime())) {
						sportPlan.setGoalStep(sportPlans.get(i).getGoalStep());

					}
				}
			}
			ctx.add(sportPlan, SportPlan.class, long.class);
			return sportPlan.getGoalStep();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 获取所有运动计划
	 * 
	 * @return
	 */
	public List<SportPlan> getAllSportPlans() {
		try {
			return ctx.queryForAll(SportPlan.class, long.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	/**
	 * 删除所有运动计划
	 * 
	 * @param sportPlans
	 */
	public void deleteAllSportPlans(List<SportPlan> sportPlans) {

		try {
			ctx.beginTransaction();
			for (SportPlan sportPlan : sportPlans) {
				ctx.delete(sportPlan, SportPlan.class, long.class);
			}
			ctx.commit();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			ctx.rollback();
		}

	}

	/**
	 * 初始化目标
	 * 
	 * @param goalStep
	 */
	public void initGoal(int goalStep) {
		try {
			ctx.beginTransaction();

			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Calendar dateCalendar = Calendar.getInstance();
			dateCalendar.set(2012, 5, 1);

			for (int i = 0; i < 5; i++) {
				String planTime = format.format(dateCalendar.getTime());
				SportPlan sportPlan = new SportPlan();
				sportPlan.setFormulateTime(format.parse(planTime));
				sportPlan.setGoalStep(goalStep + i * 200);
				ctx.add(sportPlan, SportPlan.class, long.class);
				dateCalendar.add(Calendar.DATE, 2);

			}

			ctx.commit();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ctx.rollback();
		}

	}
}
